<?php

namespace app\common\model;

use Symfony\Component\Yaml\Tests\A;
use think\Model;
use think\Db;

use app\common\library\Auth;


class User extends Model
{
    // 表名
    protected $name = 'user';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'reg_time_text',
        'healthy_text',
        'black_text',
        'last_login_time_text',
        'role_text',
        'delete_time_text'
    ];

    public function add($data){

        if (!is_array($data)){
            renderJson('传递数据不合法', 0);
        }
        $this->allowField(true)->save($data);

        return $this->uid;
    }

    /**
     * 生成用户唯一登录安全码
     * @param int $length
     */
    public function setSalt($length = 16){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
        $key = '';
        for ($i = 0; $i < $length; $i++){
            $key .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        $this->sec_code = $key;
    }
    
    public function getHealthyList()
    {
        return ['0' => __('Healthy 0'),'1' => __('Healthy 1'),'2' => __('Healthy 2'),'3' => __('Healthy 3')];
    }     

    public function getBlackList()
    {
        return ['0' => __('Black 0'),'1' => __('Black 1')];
    }     

    public function getRoleList()
    {
        return ['grouper' => __('Grouper'),'user' => __('User')];
    }     


    public function getRegTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['reg_time']) ? $data['reg_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getHealthyTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['healthy']) ? $data['healthy'] : '');
        $list = $this->getHealthyList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getBlackTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['black']) ? $data['black'] : '');
        $list = $this->getBlackList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getLastLoginTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['last_login_time']) ? $data['last_login_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getRoleTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['role']) ? $data['role'] : '');
        $list = $this->getRoleList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delete_time']) ? $data['delete_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    protected function setRegTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLastLoginTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setDeleteTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }


    public function userAttribute(){
        return $this->belongsTo('app\common\model\user\Attribute','uid','uid');
    }

    public function userReal(){
        return $this->belongsTo('app\common\model\user\Real','uid','uid');
    }

    public function userHealthy(){
        return $this->belongsTo('app\common\model\user\Healthy','uid','uid');
    }

    public function authReal(){
        return $this->belongsTo('app\common\model\auth\Real','uid','uid');
    }


    public function userBank(){

        return $this->belongsTo('app\common\model\user\Bank','uid','uid');
    }


    public function  register_act($data){

        $this->setSalt();
        $Auth = new Auth();
        $this->password = $Auth->getEncryptPassword(md5($data["password"]),$this->sec_code);
        $this->mobile = $data["mobile"];
        $this->reg_time = time();
        $this->reg_ip = request()->ip();
        $this->username = $data["username"];

        $this->member_no = "";

        $this->tao_bao_no = "";

        $this->tao_bao_id = "";

        $this->email = "";

        $this->avatar = "";

        $this->last_login_time = time();

        $this->last_login_ip = request()->ip();

        $this->device = "web";

        $this->qq = "";


        $this->alipay = "";

        $this->wxpay = "";


        $parent_name = $data["parent_name"];
        if($data["referrer_id"]) {
            $this->referrer_id = $data["referrer_id"];
        }else{
            $this->referrer_id = 0;
        }

        //halt($data);
        Db::startTrans();
        try {


            //只有派克
            $result = $this->save();
            file_put_contents( "register_user.txt", "result:".$this->referrer_id, FILE_APPEND);
            //如果存在推荐人就（获取树的位置)
            if($this->referrer_id){//有推荐人的话再别人那里添加子节点
                $parent_tree = Db::name("user_tree")->where("uid",$this->referrer_id)->find();//找到父树
                Db::name("user_tree")->where("rgt",">",$parent_tree["lft"])->where("tree_id",$parent_tree["tree_id"])->setInc("rgt",2);//更新这课树右节点条件是rgt>lft 加2
                Db::name("user_tree")->where("lft",">",$parent_tree["lft"])->where("tree_id",$parent_tree["tree_id"])->setInc("lft",2);//更新这课树左节点条件是lft>lft 加2
                $r_tree_data = [
                    "uid"=>$this->uid,
                    "username"=>$this->username,
                    "parent_id"=>$this->referrer_id,
                    "parent_name"=>$parent_name,
                    "on_time"=>time(),
                    "mobile"=>$this->mobile ,
                    "tree_id"=>$parent_tree["tree_id"],
                    "lft"=>$parent_tree["lft"]+1,
                    "rgt"=>$parent_tree["lft"]+2,
                    "level"=>$parent_tree["level"]+1
                ];
                Db::name("user_tree")->insert($r_tree_data);
            }else{//如果没有推荐人就自己创建一个树
                $_tree_data = [
                        "uid"=>$this->uid,
                        "username"=>$this->username,
                        "parent_id"=>0,
                        "parent_name"=>'',
                        "lft"=>1,
                        "rgt"=>2,
                        "tree_id"=>$this->uid,
                        "mobile"=>$this->mobile,
                        "on_time"=>time(),
                        "level"=>0
                ];
                Db::name("user_tree")->insert($_tree_data);
            }
            file_put_contents( "register_user.txt", "推荐人id:".$this->referrer_id, FILE_APPEND);
            if ($result){
                Db::commit();
                //添加一个派克默认的属性表
                $attr_data = [
                    "uid"=>$this->uid,
                    "task_count"=>15,
                    "task_day_count"=>1,
                    "person_count"=>10,
                    "task_limit_cash"=>150.00,
                    "month_task_count"=>30
                ];
                Db::name("user_attribute")->insert($attr_data);
                //添加一个派克默认的健康表
                $healy = [
                    "uid"=>$this->uid,
                    "healthy"=>"1",
                    "tao_bao_info_img"=>"",
                    "on_time"=>time()
                ];
                file_put_contents( "register_user.txt", "推荐人id:".json_encode($healy), FILE_APPEND);
                $info = Db::name("user_healthy")->insert($healy);
                $str = $this->uid;
                file_put_contents( "register_user.txt", "成功:11".$info, FILE_APPEND);
                return $this->uid;
            } else{
                Db::rollback();
            }
        } catch (\Exception $e){
            file_put_contents( "error_register.txt", "register_data".$e->getMessage().PHP_EOL, FILE_APPEND);
            Db::rollback();
        }
        return false;


    }


}
